'''
Created on Aug 7, 2009

@author: mkiyer
'''

import os
import sys

from veggie.app.application import CommandLineApplication
import veggie.db.refdb as refdb
import logging

class Bowtie(CommandLineApplication):
    '''
    An ultra-fast memory-efficient short read aligner
    http://bowtie-bio.sourceforge.net/index.shtml
    '''
    _executable = "$SW_ROOT/bioinfo/alignment/bowtie/current/bowtie"
    _indexes = {'hg18': '/hg18_illumina/hg18_illumina',
                'hg18_knownGene': '/hg18_knownGene_illumina/hg18_knownGene_illumina',
                'viral_cds_illumina': '/viral_cds_illumina/viruses_cds'}
    _indexes_path = refdb.get_bowtie_indexes_path()
    
    @staticmethod
    def get_indexes_path():
        return Bowtie._indexes_path
    @staticmethod
    def get_index(name):
        return Bowtie._indexes.get(name, None)
    @staticmethod
    def get_bowtie_path():
        return os.path.dirname(Bowtie._executable)        

    def run(self, fastq_files, output_file, 
            genome="hg18", options=None, cwd=None):
        if options:
            self.addOptions(options)
        if cwd:
            self.cwd = cwd
        if genome not in self._indexes:
            raise KeyError('indexes for genome %s not available' % genome)
        # setup environment variable for indexes and executable
        self.setenv('BOWTIE_INDEXES', Bowtie.get_indexes_path())
        self.setenv('PATH', ':'.join([os.path.dirname(self._executable),
                                      os.environ['PATH']]))
        output_file = os.path.join(self.cwd, output_file)
        # for now can only accept fastq files
        self.addOption('-q', None)
        if len(fastq_files) == 1:
            self.args = [self._indexes[genome], 
                         fastq_files[0], 
                         output_file]
        elif len(fastq_files) == 2:
            self.args = [self._indexes[genome],
                         "-1 %s" % fastq_files[0],
                         "-2 %s" % fastq_files[1], 
                         output_file]
        else:
            raise ValueError("must pass either 1 or 2 fastq files")
        # debug
        logging.debug(self.getCommandLine())            
        # run the program        
        return self()

    def run_single_best(self, fastq_files, output_file, 
                        genome="hg18", options=None, cwd=None):        
        # options for single-best alignment
        self.addOptions({'-m': 1,
                         '-k': 1,
                         '--best': None})
        return self.run(self, fastq_files, output_file, genome, options, cwd)
